import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);

import { login} from '@/api/configure.js';
import { deepClone ,mergeUrls, getUserInfo , getRegistrationID} from '@/util/util.js';
const store = new Vuex.Store({
	state: {
		hasLogin: false,
		userInfo: {},
		mediaOtherParams: {},
	},
	mutations: {
		login(state, {userInfo}) {
			state.hasLogin = true;
			state.userInfo = userInfo;
		},
		logout(state) {
			state.hasLogin = false
			state.userInfo = {};
		},
		getUserInfo(state, {userInfo}) {
			state.userInfo = userInfo;
		},
		setMediaOtherParams(state, {params}) {
			state.mediaOtherParams = params;
		},
		getMediaOtherParams(state) {}
	},
	actions: {
		async login({commit, state}, {data}) {
			return await new Promise((resolve, reject) => {
				login(data).then(( res ) => {
					uni.setStorageSync('userName', data.username);
					uni.setStorageSync('password', data.password);
					uni.setStorageSync('token', res.token);
					resolve(res.data);
				}, (err)=> {
					reject(0);
				})
			})
		},
		async logout({commit, dispatch, state}) {
			return await new Promise(( resolve, reject) => {
				uni.removeStorageSync('userName');
				uni.removeStorageSync('password');
				uni.removeStorageSync('token');
				uni.reLaunch({
					url: '/pages/login/login'
				});
			})
		},
		async getUserInfo({commit, dispatch, state}) {
			return await new Promise(( resolve, reject) => {
				let userInfo = deepClone(uni.getStorageSync('userInfo'));
				
				commit({type: 'getUserInfo', userInfo: userInfo});
				
				resolve(state.userInfo)
			})
		},
		async setMediaOtherParams({commit, dispatch, state}, {params}) {
			return await new Promise((resolve, reject) => {
				commit({type: 'setMediaOtherParams', params: params});
				resolve(state.mediaOtherParams);
			})
		}
	}
});
export default store;